<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8" />
    <title>营销统计 - 订餐管理系统</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <link rel="stylesheet" href="marketing-statistics.css" />
    <link rel="stylesheet" href="通用新页面css.css" />
</head>
<body>
<div id="app">
    <div class="container">
        <!-- 侧边栏导航 -->
        <div class="sidebar">
            <a href="mainpage.html" class="sidebar-item">首页</a>
            <a href="dish-management.html" class="sidebar-item">菜品管理</a>
            <a href="order-management.html" class="sidebar-item">订单管理</a>
            <a href="marketing-statistics.html" class="sidebar-item active">营销统计</a>
            <a href="UserPage.html" class="sidebar-item">用户管理</a>
        </div>
        <div class="content">
            <div class="header">
                <h1>{{ month }}月营销统计</h1>
            </div>
            <!-- 统计数据卡片 -->
            <div class="stats-cards">
                <div class="stat-card">
                    <h3>总销售额</h3>
                    <p class="stat-value sales-color">¥{{ totalSales.toFixed(2) }}</p>
                </div>
                <div class="stat-card">
                    <h3>订单总数</h3>
                    <p class="stat-value orders-color">{{ totalOrders }}</p>
                </div>
                <div class="stat-card">
                    <h3>平均客单价</h3>
                    <p class="stat-value avg-color">¥{{ avgOrderValue.toFixed(2) }}</p>
                </div>
            </div>
            <!-- 图表区域 -->
            <div class="charts-container">
                <div class="chart-wrapper">
                    <div id="salesChart" class="chart"></div>
                </div>
                <div class="chart-wrapper">
                    <div id="dishSalesChart" class="chart"></div>
                </div>
            </div>
            <!-- 热销菜品表格 -->
            <div class="table-container">
                <h3>热销菜品TOP10</h3>
                <table class="data-table">
                    <thead>
                    <tr>
                        <th>排名</th>
                        <th>菜品名称</th>
                        <th>销售数量</th>
                        <th>销售金额</th>
                        <th>占比</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(dish, index) in hotDishes" :key="dish.dishId">
                        <td>{{ index + 1 }}</td>
                        <td>{{ dish.dishName }}</td>
                        <td>{{ dish.quantity }}</td>
                        <td>¥{{ dish.subtotal.toFixed(2) }}</td>
                        <td>{{ (dish.percentage * 100).toFixed(1) }}%</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    const { createApp, reactive, ref, onMounted } = Vue;
    createApp({
        setup() {
            // 统计参数与数据
            const month = ref();
            const timeRange = ref("month");
            const totalSales = ref(0);
            const totalOrders = ref(0);
            const avgOrderValue = ref(0);
            const hotDishes = ref([]);
            const monthlyOrders = ref([]); // 存储当前月订单数据
            let salesChart = null;
            let dishSalesChart = null;

            // 初始化图表
            const initCharts = () => {
                const salesChartDom = document.getElementById('salesChart');
                salesChart = echarts.init(salesChartDom);
                const dishChartDom = document.getElementById('dishSalesChart');
                dishSalesChart = echarts.init(dishChartDom);
            };

            // 请求当前月订单数据（不传递任何参数）
            const fetchMonthlyOrders = async () => {
                try {
                    // 不传递任何参数的GET请求
                    const response = await axios.get('/t-order/currentMthOrd', {
                        headers: {
                            Authorization: "Bearer " + localStorage.getItem("food_token")
                        }
                    });
                    console.log(response.data.data)
                    monthlyOrders.value = response.data.data; // 假设数据在response.data.data中
                    calculateStatistics(); // 计算统计数据
                } catch (error) {
                    console.error('获取订单数据失败:', error);
                    alert('获取统计数据失败，请重试');
                }
            };

            // 计算统计指标
            const calculateStatistics = () => {
                // 1. 基础指标（总销售额、订单总数、平均客单价）
                totalOrders.value = monthlyOrders.value.length;

                // 处理销售额计算，兼容数字和BigDecimal字符串
                totalSales.value = monthlyOrders.value.reduce((sum, order) => {
                    // 处理可能的字符串金额（如"100.00"）
                    const amount = typeof order.totalAmount === 'string'
                        ? parseFloat(order.totalAmount)
                        : order.totalAmount;
                    return sum + (amount || 0);
                }, 0);

                avgOrderValue.value = totalOrders.value > 0
                    ? totalSales.value / totalOrders.value
                    : 0;

                // 2. 菜品销售统计
                const dishMap = new Map(); // key: dishId, value: 累计数据
                monthlyOrders.value.forEach(order => {
                    if (order.dishItems && Array.isArray(order.dishItems)) {
                        order.dishItems.forEach(item => {
                            if (!dishMap.has(item.dishId)) {
                                dishMap.set(item.dishId, {
                                    dishId: item.dishId,
                                    dishName: item.dishName || '未知菜品',
                                    quantity: 0,
                                    subtotal: 0
                                });
                            }
                            const dish = dishMap.get(item.dishId);
                            dish.quantity += item.quantity || 0;

                            // 处理可能的字符串金额
                            const subtotal = typeof item.subtotal === 'string'
                                ? parseFloat(item.subtotal)
                                : item.subtotal;
                            dish.subtotal += subtotal || 0;
                        });
                    }
                });

                // 转换为数组并计算占比
                const dishList = Array.from(dishMap.values());

                // 计算占比并排序（取TOP10）
                const totalDishSales = dishList.reduce((sum, d) => sum + d.subtotal, 0);
                hotDishes.value = dishList
                    .sort((a, b) => b.quantity - a.quantity) // 按销量排序
                    .slice(0, 10)
                    .map(dish => ({
                        ...dish,
                        percentage: totalDishSales > 0 ? dish.subtotal / totalDishSales : 0
                    }));

                // 更新图表
                updateSalesChart();
                updateDishSalesChart();
            };

            // 更新销售趋势图（按日期聚合）
            const updateSalesChart = () => {
                // 按日期分组统计销售额
                const dateMap = new Map();
                monthlyOrders.value.forEach(order => {
                    if (order.createTime) {
                        const date = order.createTime.split('T')[0]; // 提取日期部分（yyyy-MM-dd）
                        if (!dateMap.has(date)) {
                            dateMap.set(date, 0);
                        }

                        // 处理可能的字符串金额
                        const amount = typeof order.totalAmount === 'string'
                            ? parseFloat(order.totalAmount)
                            : order.totalAmount;

                        dateMap.set(date, dateMap.get(date) + (amount || 0));
                    }
                });

                // 排序日期并提取数据
                const sortedDates = Array.from(dateMap.keys()).sort();
                const salesData = sortedDates.map(date => dateMap.get(date));

                // 设置图表选项
                const option = {
                    title: { text: '销售趋势', left: 'center' },
                    tooltip: { trigger: 'axis' },
                    legend: { data: ['销售额'], bottom: 0 },
                    grid: { left: '3%', right: '4%', bottom: '15%', top: '15%', containLabel: true },
                    xAxis: { type: 'category', boundaryGap: false, data: sortedDates },
                    yAxis: { type: 'value', axisLabel: { formatter: '¥{value}' } },
                    series: [{
                        name: '销售额',
                        type: 'line',
                        data: salesData,
                        lineStyle: { color: '#007bff' },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: 'rgba(0, 123, 255, 0.3)' },
                                { offset: 1, color: 'rgba(0, 123, 255, 0)' }
                            ])
                        },
                        smooth: true
                    }]
                };
                salesChart.setOption(option);
            };

            // 更新菜品销售占比图
            const updateDishSalesChart = () => {
                const option = {
                    title: { text: '菜品销售占比', left: 'center' },
                    tooltip: { trigger: 'item' },
                    legend: {
                        orient: 'vertical',
                        left: 10,
                        data: hotDishes.value.map(d => d.dishName)
                    },
                    series: [{
                        name: '销售金额',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: { show: false, position: 'center' },
                        emphasis: {
                            label: { show: true, fontSize: 16, fontWeight: 'bold' }
                        },
                        labelLine: { show: false },
                        data: hotDishes.value.map(d => ({
                            name: d.dishName,
                            value: d.subtotal
                        }))
                    }],
                    color: ['#007bff', '#28a745', '#dc3545', '#ffc107', '#17a2b8', '#6610f2', '#fd7e14', '#20c997', '#e83e8c', '#6f42c1']
                };
                dishSalesChart.setOption(option);
            };

            // 响应窗口大小变化
            const handleResize = () => {
                salesChart?.resize();
                dishSalesChart?.resize();
            };

            // 页面加载时初始化
            onMounted(() => {
                month.value = String(new Date().getMonth() + 1);
                initCharts();
                fetchMonthlyOrders(); // 加载数据
                window.addEventListener('resize', handleResize);
            });

            return {
                month,
                timeRange,
                totalSales,
                totalOrders,
                avgOrderValue,
                hotDishes
            };
        }
    }).mount("#app");
</script>
</body>
</html>
